package com.mcxx.modules.miniSalvation.order.service.write;

import com.mcxx.common.exception.BizException;
import com.mcxx.modules.miniSalvation.order.dao.read.StandardReadDao;
import com.mcxx.modules.miniSalvation.order.dao.write.StandardWriteDao;
import com.mcxx.modules.miniSalvation.order.dto.CheckDTO;
import com.mcxx.modules.miniSalvation.order.entity.StandardEntity;
import com.mcxx.modules.miniSalvation.order.entity.StandardHistoryEntity;
import com.mcxx.modules.miniSalvation.order.service.read.StandardReadService;
import com.mcxx.modules.system.dto.StandardDTO;
import com.mcxx.modules.temporary.order.service.read.TmpOrderReadService;
import com.mcxx.util.CommonUtil;
import com.mcxx.util.Constant;
import com.mcxx.util.FailureCode;
import com.yinhai.ta404.core.security.vo.UserAccountVo;
import com.yinhai.ta404.core.transaction.annotation.TaTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@TaTransactional
public class StandardWriteService {
    @Autowired
    private StandardWriteDao standardWriteDao;
    @Autowired
    private StandardReadService standardReadService;
    @Autowired
    private StandardHistoryWriteService standardHistoryWriteService;
    @Autowired
    private TmpOrderReadService tmpOrderReadService;



    public int insertIgnoreNull(StandardEntity standardEntity) {
        return standardWriteDao.insertIgnoreNull(standardEntity);
    }


    public int update(StandardEntity standardEntity) {
        return standardWriteDao.update(standardEntity);
    }


    public int updateIgnoreNull(StandardEntity standardEntity) {
        return standardWriteDao.updateIgnoreNull(standardEntity);
    }


    public void addStandard(StandardEntity standardEntity) {
        standardEntity.setId(Constant.getUUID());
        standardEntity.setStatus(Constant.StandardStatus.NOT_ENABLE);
        standardEntity.setStandType(standardEntity.getType());
        standardEntity.setStartDate(standardEntity.getReleaseDate());
        int rst = standardWriteDao.insertIgnoreNull(standardEntity);
        if(rst <= 0){
            throw new BizException(FailureCode.ERR_50005);
        }
    }


    public void delSalvationStandard(String id) {
        standardWriteDao.deleteById(id);
    }


    public int updateSalvationStandardStatus(String standardId, String status, String gearCode, String areaCode, String orgId,String businessType) {

        if(Constant.StandardStatus.DISABLE.equals(status) || Constant.StandardStatus.FROZEN.equals(status)){
            areaCode = areaCode.substring(0,6);
            int i = standardReadService.getOrderByGear("2", gearCode, areaCode);
            if(i > 0){
                throw new BizException("-1","当前救助业务在保人数为:"+i+"，不能冻结或停用");
            }

            if(Constant.BusinessCode.LINSHI.equals(businessType)){
                int auditNum = tmpOrderReadService.getAuditNum(areaCode);
                if(auditNum > 0){
                    throw new BizException("-1","当前救助业务正在乡镇审核业务为:"+auditNum+"，不能冻结或停用");
                }

            }


        }else if(Constant.StandardStatus.ENABLE.equals(status)){

            int i = standardReadService.countSalvaLSType(areaCode, standardId);
            if(i > 0){
                throw new BizException("-1","当前救助业务已启用同类型的标准,请勿重复启用");
            }
        }


        StandardEntity standardEntity = new StandardEntity();
        standardEntity.setId(standardId);
        standardEntity.setStatus(status);
        int i = standardWriteDao.updateStatus(standardEntity);
        if(i <= 0){
            throw new BizException("-1","操作异常,请联系管理员");
        }

        standardWriteDao.updateStatusChild(standardEntity);
        return 1;
    }


    public int updateChildState(String pId){ return standardWriteDao.updateChildState(pId); }





    public void saveStandard(StandardDTO standardDTO, UserAccountVo userAccountVo, String welfareId){


        this.insertStandardHistory(standardDTO, userAccountVo, welfareId);


        this.updateStandard(standardDTO, userAccountVo);
    }


    public void updateStandard(StandardDTO parentStandardDTO, UserAccountVo userAccountVo){

        StandardEntity standardEntity = new StandardEntity();


        BeanUtils.copyProperties(parentStandardDTO, standardEntity);
        standardEntity.setOperator(userAccountVo.getUserId());
        standardEntity.setOrgId(userAccountVo.getOrgId());
        standardEntity.setStatus(Constant.StandardStatus.ENABLE);
        standardEntity.setAreaCode(userAccountVo.getAreaCode());
        int rst = standardWriteDao.update(standardEntity);
        if(rst <= 0){
            throw new BizException("-1", "调标标准失败");
        }


        for(StandardDTO standard : parentStandardDTO.getStandardList()){
            standardEntity = this.packageStandardEntity(parentStandardDTO, standard, userAccountVo);

            if(CommonUtil.invalidArgs(standard.getId())){
                standardEntity.setId(Constant.getUUID());
                rst = standardWriteDao.insertIgnoreNull(standardEntity);
            }else{
                rst = standardWriteDao.updateIgnoreNull(standardEntity);
            }
            if(rst <= 0){
                throw new BizException("-1", "调标标准失败");
            }
        }
    }


    public void insertStandardHistory(StandardDTO parentStandardDTO, UserAccountVo userAccountVo, String welfareId){

        Map<String, StandardDTO> newStandardDTOMap =
                parentStandardDTO.getStandardList().stream()
                        .filter(standard -> !CommonUtil.invalidArgs(standard.getId()))
                        .collect(Collectors.toMap(StandardDTO::getId, StandardDTO -> StandardDTO));

        newStandardDTOMap.put(parentStandardDTO.getId(), parentStandardDTO);


        List<StandardEntity> standardList = standardReadService.getStandardForGroup(parentStandardDTO.getId());


        String historyParentId = Constant.getUUID();
        List<StandardHistoryEntity> standardHistoryList = new ArrayList<>();
        for(StandardEntity oldStandardEntity : standardList){
            StandardDTO newStandardDTO = newStandardDTOMap.get(oldStandardEntity.getId());
            StandardHistoryEntity standardHistoryEntity =  this.packageStandardHistoryEntity(oldStandardEntity,
                    userAccountVo,
                    newStandardDTO,
                    historyParentId,
                    parentStandardDTO,
                    welfareId);
            standardHistoryList.add(standardHistoryEntity);
        }

        if(!standardHistoryList.isEmpty()){
            int rst = standardHistoryWriteService.insertList(standardHistoryList);
            if(rst <= 0){
                throw new BizException("-1", "调标标准失败");
            }
        }
    }


    public StandardHistoryEntity packageStandardHistoryEntity(StandardEntity oldStandardEntity,
                                                              UserAccountVo userAccountVo,
                                                              StandardDTO newStandardDTO,
                                                              String historyParentId,
                                                              StandardDTO parentStandardDTO,
                                                              String welfareId){
        StandardHistoryEntity standardHistoryEntity = new StandardHistoryEntity();

        BeanUtils.copyProperties(oldStandardEntity, standardHistoryEntity);
        if(CommonUtil.invalidArgs(oldStandardEntity.getParentId())){

            standardHistoryEntity.setId(historyParentId);
        }else{

            standardHistoryEntity.setId(Constant.getUUID());
            standardHistoryEntity.setParentId(historyParentId);
        }
        standardHistoryEntity.setStandardId(oldStandardEntity.getId());
        standardHistoryEntity.setCreateTime(new Date());
        standardHistoryEntity.setOperator(userAccountVo.getUserId());
        standardHistoryEntity.setOrgId(userAccountVo.getOrgId());
        standardHistoryEntity.setAreaCode(userAccountVo.getAreaCode());
        standardHistoryEntity.setStatus("1");
        standardHistoryEntity.setNewReleaseDate(parentStandardDTO.getReleaseDate());
        standardHistoryEntity.setNewReleaseRule(parentStandardDTO.getReleaseRule());
        standardHistoryEntity.setNewStandardFileName(parentStandardDTO.getStandardFileName());
        standardHistoryEntity.setNewStandardFileNo(parentStandardDTO.getStandardFileNo());
        standardHistoryEntity.setNewStandardMoney(newStandardDTO.getStandardMoney());
        standardHistoryEntity.setNewGearStart(newStandardDTO.getGearStart());
        standardHistoryEntity.setNewGearEnd(newStandardDTO.getGearEnd());

        standardHistoryEntity.setWelfareId(welfareId);

        return standardHistoryEntity;
    }



    public StandardEntity packageStandardEntity(StandardDTO parentStandardDTO, StandardDTO standard, UserAccountVo userAccountVo){
        StandardEntity standardEntity = new StandardEntity();
        BeanUtils.copyProperties(standard, standardEntity);
        standardEntity.setOperator(userAccountVo.getUserId());
        standardEntity.setOrgId(userAccountVo.getOrgId());
        standardEntity.setBusinessType(parentStandardDTO.getBusinessType());
        standardEntity.setStandType(parentStandardDTO.getType());
        standardEntity.setReleaseDate(parentStandardDTO.getReleaseDate());
        standardEntity.setStartDate(parentStandardDTO.getStartDate());
        standardEntity.setEndDate(parentStandardDTO.getEndDate());
        standardEntity.setStandardFileName(parentStandardDTO.getStandardFileName());
        standardEntity.setReleaseRule(parentStandardDTO.getReleaseRule());
        standardEntity.setStandardFileNo(parentStandardDTO.getStandardFileNo());
        standardEntity.setAreaCode(userAccountVo.getAreaCode());
        standardEntity.setStatus(Constant.StandardStatus.ENABLE);
        standardEntity.setParentId(parentStandardDTO.getId());

        return standardEntity;
    }


}
